import React, {memo, MouseEvent, useState, Dispatch, useEffect} from 'react';
import { BuilderInformation } from './builder-information/BuilderInformation';
import { BuilderWidgetPanel } from './builder-widget-panel/BuilderWidgetPanel';
import { BuilderEditor } from './builder-editor/BuilderEditor';
import { useStateReducer, useInformationReducer } from './hooks';
import { isDevelopment } from '@bastet/utils';
import type { IComponent, IComponentType } from '@bastet/widgets';
import './builder-layout.less';
import './style/index.less';


const importAsync = (require as any).context('/src/widget', true, /(index)\.tsx$//*, 'sync'*/);
const comps: string[] = importAsync.keys();
const widgets: Map<string, any> = new Map()
comps.forEach(item => {
  const widget = importAsync(item)
  widget && widgets.set(widget.settings.name, widget)
})
console.log('widgets: => ', widgets)

// console.log(originalState)
export default memo(() => {
  const [ state, dispatch, changeField ] = useStateReducer()
  const [ activePath, setActivePath ] = useState<string>()
  const [ information, setInformation ] = useInformationReducer<IComponent>(state as IComponent[])
  const __onClick = (event: MouseEvent <Element>, data: IComponent) => {
    console.log('BuilderLayout: ——————————————__onClick => ', data, information?.path)
    if (data) {
      if (!information || data.path !== information?.path || !information?.path) {
        setInformation(data as any);
      }
      setActivePath(data.path);
    } else  {
      // (setInformation as any)(null)
    }
  }

  useEffect(() => {
    /*requestGet('http://localhost:4003/api/scenes').then(({ code, data }) => {
      if (code === 0) {
        if (Array.isArray(data)) {
          dispatch(data)
        } else {
          dispatch([data])
        }
      }
    })*/

    // 如果是开发环境，优先使用 widgets.json 中配置的组件
    if (isDevelopment) {

    }
    /*requestGet('http://localhost:4003/api/widget').then(({ code, data }) => {
      if (code === 0) {
        if (Array.isArray(data)) {
          dispatch(data)
        } else {
          dispatch([data])
        }
      }
    })*/
  }, [])

  // console.log('originalState: => ', state)
  console.log(`\n activePath: => ${activePath};information: => `, information);
  return (
    <div className="root-builder">
      <BuilderWidgetPanel widgets={widgets} />
      <BuilderEditor
        defaultStyle={{ width: `calc(100vw - ${!information?.path ? 100 : 420}px)` }}
        state={state}
        activePath={activePath}
        dispatch={dispatch as Dispatch<any>}
        importAsync={importAsync}
        widgets={widgets}
        onClick={__onClick}
      />
      {
        information?.path && (
          <BuilderInformation
            information={information}
            dispatch={changeField as Dispatch<any>}/>
        )
      }
    </div>
  )
})
